package com.example.registration.controller;

import com.example.registration.pojo.Admin;
import com.example.registration.service.LoginService;
import com.example.registration.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: registration
 * @Description: $
 * @Param: $
 * @return: $
 * @Author: xieyongde
 * @Date: 2019-08-19
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginService loginService;

    public LoginService getLoginService() {
        return loginService;
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/logout.htm", method = RequestMethod.POST)
    @ResponseBody
    public Object logout(HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            session.invalidate();
            map.put("result", true);
            map.put("message", "退出成功");
            map.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "退出访问异常：" + e);
        }
        return map;
    }

    /**
     * 登录
     *
     * @param session
     * @param name
     * @param userPassword
     * @return
     */
    @RequestMapping(value = "/login.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map login(HttpSession session, String name, String userPassword) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        /**
         * success-请求是否成功
         * result-登录是否成功
         * message-提示信息
         */
        try {
            //模拟网络延迟
            //Thread.sleep(1000*3);
            map = loginService.login(name, userPassword);
            Admin admin = (Admin) map.get("data");
            session.setAttribute(Constants.USER_LOGIN_KEY, admin);
            map.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "登录接口访问异常:" + e);
        }
        return map;
    }
}
